package demo2;

import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int usedSize;

    //数组的默认大小为10
    public TestHeap() {
        this.elem = new int[10];
    }


    //创建一个堆
    //建堆的时间复杂度 : O(n)
    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            usedSize++;
        }
        createHeapchild();
    }
    public void createHeapchild() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(parent);
        }
    }
    //向下调整  时间复杂度 : 树的高度
    public void shiftDown(int parent) {
        int child = parent * 2 + 1;
        while (child < usedSize) {
            if ((child + 1 < usedSize) && (elem[child + 1] > elem[child])) {
                child = child + 1;
            }
            if (elem[parent] < elem[child]) {
                swap(parent,child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }
    public void swap(int x, int y) {
        int temp = elem[x];
        elem[x] = elem[y];
        elem[y] = temp;
    }
    //向上调整建堆的时间复杂度是 O(n*logn)
    public void offer(int val) {
        if(isFull()) {
            this.elem = Arrays.copyOf(this.elem,this.elem.length * 2);
        }
        this.elem[usedSize++] = val;
        shiftUp(usedSize - 1);
    }
    private boolean isFull() {
        return usedSize == elem.length;
    }
    //向上调整
    public void shiftUp(int end) {
        int parent = (end - 1) / 2;
        while (end > 0) {
            if (elem[end] > elem[parent]) {
                swap(end,parent);
                end = parent;
                parent = (parent - 1) / 2;
            } else {
                break;
            }
        }
    }
    //删除最大值
    public void pop() {
        swap(0,usedSize - 1);
        usedSize--;
        shiftDown(0);
    }
}
